package com.xdf.wxbebarrel.utils;


import com.xdf.wxbebarrel.model.DBConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ClassName:DynamicDBUtils
 * @Description:TODO
 * @Author:chanchaw
 * @Date:2019-11-18 16:33
 * @Version:1.0
 **/
@Component
public class DynamicDBUtils {
    @Autowired
    private DataSource dynamicDataSource;

    public List<Map<String,Object>> queryForListCallProc(List<String> procAndParams){
        String sqlString = callProc2SQLString(procAndParams);
        return queryForList(sqlString);
    }

    public List<Map<String,Object>> queryForList(String sql){
        DataSource targetDataSource = dynamicDataSource;
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(targetDataSource);
        List<Map<String,Object>> list = jdbcTemplate.queryForList(sql,new HashMap<>());
        return list;
    }

    public String callProc2SQLString(List<String> callProc){
        if( callProc == null || callProc.size()<=0 ) return "";
        String sqlString = "call " + callProc.get(0) + "(";
        String comma = ",";
        for (int i = 1; i < callProc.size(); i++) {
            if(i == 1)
                comma ="";
            else
                comma =",";

            String currentItem = Optional.ofNullable(callProc.get(i)).orElse("");
            if(currentItem.length()<=0)
                sqlString = sqlString + comma + "''";
            else
                sqlString = sqlString + comma + "'" + callProc.get(i) + "'";
        }

        sqlString += ")";

        return sqlString;
    }

    public int cud(String sql){
        NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dynamicDataSource);
        return jdbcTemplate.update(sql, new HashMap<>());
    }

}
